package com.miui.systemui.tools

import java.awt.event.ActionEvent
import javax.swing.GroupLayout
import javax.swing.JButton
import javax.swing.JDialog
import javax.swing.JLabel
import javax.swing.JScrollPane
import javax.swing.JTextArea
import javax.swing.JTextField
import javax.swing.LayoutStyle
import javax.swing.SwingUtilities


class Figma2xmlDialog : JDialog() {
    private var isRequest = false;
    private fun initComponents() {
        jLabel1 = JLabel()
        jTextField1 = JTextField()
        jScrollPane1 = JScrollPane()
        jTextArea1 = JTextArea()
        jButton1 = JButton()
        jLabel2 = JLabel()
        jTextField2 = JTextField()

        defaultCloseOperation = DISPOSE_ON_CLOSE

        jLabel1!!.text = "Figma URL :"

        jTextField1!!.addActionListener { evt -> jTextField1ActionPerformed(evt) }

        jTextArea1!!.columns = 20
        jTextArea1!!.rows = 8
        jTextArea1!!.text = "输出层"
        jScrollPane1!!.setViewportView(jTextArea1)

        jButton1!!.text = "开始解析"
        jButton1!!.addActionListener { evt -> jButton1ActionPerformed(evt) }

        jLabel2!!.text = "token :"

        jTextField2!!.addActionListener { evt -> jTextField2ActionPerformed(evt) }

        val token = Figma2xmlSettings.getSettingsInstance().mToken;
        jTextField2!!.text = token

        val layout = GroupLayout(contentPane)
        contentPane.layout = layout
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(26, 26, 26).addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addGroup(
                        layout.createSequentialGroup().addComponent(jLabel2).addGap(18, 18, 18)
                            .addComponent(jTextField2)
                    ).addComponent(
                        jScrollPane1, GroupLayout.PREFERRED_SIZE, 668, GroupLayout.PREFERRED_SIZE
                    ).addGroup(
                        layout.createSequentialGroup().addComponent(
                            jLabel1, GroupLayout.PREFERRED_SIZE, 84, GroupLayout.PREFERRED_SIZE
                        ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(
                            jTextField1, GroupLayout.PREFERRED_SIZE, 411, GroupLayout.PREFERRED_SIZE
                        ).addComponent(
                            jButton1, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE
                        )
                    )
                ).addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt())
            )
        )
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addContainerGap(19, Short.MAX_VALUE.toInt())
                    .addGroup(
                        layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2).addComponent(
                                jTextField2,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE
                            )
                    ).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                        layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                            layout.createSequentialGroup().addComponent(
                                jLabel1, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE
                            ).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(
                                    jScrollPane1,
                                    GroupLayout.PREFERRED_SIZE,
                                    294,
                                    GroupLayout.PREFERRED_SIZE
                                )
                        ).addGroup(
                            layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(
                                jTextField1,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE
                            ).addComponent(
                                jButton1,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE
                            )
                        )
                    ).addContainerGap()
            )
        )

        pack()
    } // </editor-fold>                        

    private fun jTextField1ActionPerformed(evt: ActionEvent) {

    }

    private fun jButton1ActionPerformed(evt: ActionEvent) {
        if (jTextField2!!.text.isEmpty()) {
            MessageDialogUtils.createCustomNotification("token不能为null")
            return
        }
        if (jTextField1!!.text.isEmpty()) {
            MessageDialogUtils.createCustomNotification("figma链接不能为null")
            return
        }

        //保存token
        Figma2xmlSettings.getSettingsInstance().setToken(jTextField2!!.text.trim())

        val parsedFigmaUrl = ParsedFigmaUrl.parseFigmaUrl(jTextField1!!.text.trim())
        if (parsedFigmaUrl == null) {
            jTextArea1!!.text = "请输入正确的url链接"
            return
        }

        if (isRequest) {
            return
        }

        Thread(object : Runnable {
            override fun run() {
                try {

                    updateTextArea("正在请求中,请等待.....\n");
                    val fileId = parsedFigmaUrl.fileId // 替换为您的文件 ID
                    val nodeId = parsedFigmaUrl.nodeId // 替换为节点 ID，或传 null 获取整个文件
                    println("fileId:" + parsedFigmaUrl.fileId + "\n" + "nodeId:" + nodeId)
                    var jsonResponse = FigmaAPI.fetchFigmaData(fileId, nodeId)
                    println(jsonResponse)

                    // 解析 JSON 字符串到 JsonElement
                    // 解析 JSON 字符串到 JsonElement
                    jsonResponse = JsonCleaner.cleanJson(
                        jsonResponse,
                        "scrollBehavior",
                        "blendMode",
                        "prototypeDevice",
                        "backgroundColor",
                        "constraints",
                        "interactions",
                        "strokes",
                        "strokeAlign",
                        "strokeWeight",
                        "characterStyleOverrides",
                        "styleOverrideTable",
                        "lineTypes",
                        "lineIndentations",
                        "version",
                        "role",
                        "editorType",
                        "linkAccess",
                        "componentSets",
                        "schemaVersion",
                        "styles",
                        "lastModified",
                        "version",
                        "presetIdentifier",
                        "flowStartingPoints",
                        "thumbnailUrl",
                        "filters",
                        "bottomBar",
                        "BottomBar",
                        "Bottom Bar",
                        "statusBar",
                        "StatusBar",
                        "Status Bar",
                        "Tab Bar",
                        "状态栏",
                        "导航栏",
                        "absoluteRenderBounds",
                        "id",
                        "imageRef",
                        "lineHeightUnit",
                        "layoutVersion",
                        "opentypeFlags",
                        "components",
                        "lineHeightPx",
                        "lineHeightPercent",
                        "letterSpacing"
                    )
                    jTextArea1!!.text = jTextArea1!!.text + "\n" + "jsonResponse:" + jsonResponse
                    isRequest = true
                    jTextArea1!!.text += "\n\n\n"
                    AiModel.requestAi(
                        prompt = Prompt.promptSystem,
                        jsonResponse,
                        success = { data: String ->
                            println("data:" + data)
                            if ("[DONE]".equals(data)) {
                                isRequest = false;
                                return@requestAi
                            }
                            updateTextArea(data);
                        },
                        fail = { error: String ->
                            println("error:" + error)
                            isRequest = false
                            jTextArea1!!.text = "请求出错:\n" + error

                        })

                } catch (e: Exception) {
                    e.printStackTrace()
                    jTextArea1!!.text = "请求出错:\n" + e.printStackTrace()
                }
            }
        }).start()
    }

    private fun jTextField2ActionPerformed(evt: ActionEvent) {
        // TODO add your handling code here:
    }


    // Variables declaration - do not modify                     
    private var jButton1: JButton? = null
    private var jLabel1: JLabel? = null
    private var jLabel2: JLabel? = null
    private var jScrollPane1: JScrollPane? = null
    private var jTextArea1: JTextArea? = null
    private var jTextField1: JTextField? = null
    private var jTextField2: JTextField? = null // End of variables declaration                   

    /**
     * Creates new form NewJDialog
     */
    init {
        initComponents()
    }

    private fun updateTextArea(newText: String) {
        SwingUtilities.invokeLater {
            jTextArea1?.append(newText)
            jTextArea1?.paintImmediately(jTextArea1?.getBounds());
        }
    }
}
